package com.aizuda.easyManagerTool.service.terminal.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class StringBufferListener {

    private StringBuffer buffer;
    private int threshold;

    private TerminalSessionManager.Manager manager;

    public StringBufferListener(int threshold, TerminalSessionManager.Manager manager) {
        this.buffer = new StringBuffer();
        this.threshold = threshold;
        this.manager = manager;
    }

    public StringBufferListener(TerminalSessionManager.Manager manager) {
        this.buffer = new StringBuffer();
        this.threshold = 1024;
        this.manager = manager;
    }

    public void append(String str){
        buffer.append(str);
        int currentSize = buffer.length();
        if (currentSize >= threshold) {
            onListener();
        }
    }

    public void onListener(){
        // 写文件
        Thread thread = new Thread(() -> {
            try {
                // 将字符串追加写入文件
                synchronized (buffer) {
                    Path path = Paths.get(this.manager.getManagerLog().getPath());
                    String str = buffer.toString();
                    // 处理 clear 命令
                    str = str.replaceAll("\\u001b\\[2J", "")
                            // 处理 clear换行命令
                            .replaceAll("\u001B\\[3;J\u001B\\[H\u001B]0;", "\u001B]0;")
                            // 处理 top 命令
                            .replaceAll("\u001B\\[\\?1h\u001B=\u001B\\[\\?25l\u001B\\[H\u001B\\(B\u001B", "\u001B]");
                    Files.write(path, str.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
                    buffer.setLength(0);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        thread.setName("终端监听文件写入-"+this.manager.getManagerLog().getPath());
        thread.start();
    }

}
